<template>
  <AdVxeModal
    v-bind="$attrs"
    @register="register"
    :id="formIndex"
    :title="`${t('routes.system.message.message.title')} - ${FormModeEntityRef.Display}`"
    :help-message="`${t('common.form')}：${formIndex}`"
    :cancelText="t('common.cancelText')"
    :close-func="handleClose"
    :okText="FormModeEntityRef.OkBtnTitle"
    @ok="handleOk"
    @open-change="handleOpenChange"
    width="50%"
  >
    <BasicForm @register="registerForm" @contextmenu="handleContextMenu">
      <template #icon="{ model, field }">
        <ImageSelector
          v-model:value="model[field]"
          :width="50"
          accept=".jpg,.jpeg,.png,.bmp,.ico,.gif"
          :max-size="0.5"
          :disabled="
            FormModeEntityRef.FormMode !== FormModeEnum.Add &&
            FormModeEntityRef.FormMode !== FormModeEnum.Edit
          "
        />
      </template>
      <template #sendTo="{}">
        <Tooltip :title="t('routes.system.message.toUsersText')">
          <a-button type="primary" @click="handleUserTransferModalOpen">
            <Icon icon="majesticons:users-line" />
          </a-button>
        </Tooltip>
        <Tooltip :title="t('routes.system.message.toOrganizationsText')" class="ml-2">
          <a-button type="primary" @click="handleOrganizationTransferModalOpen">
            <Icon icon="clarity:organization-line" />
          </a-button>
        </Tooltip>
        <Tooltip :title="t('routes.system.message.toRolesText')" class="ml-2">
          <a-button type="primary" @click="handleRoleTransferModalOpen">
            <Icon icon="carbon:user-role" />
          </a-button>
        </Tooltip>
        <Authority :value="'Root.Admin.Msg.Message.ReadReceiver'">
          <Tooltip
            :title="t('routes.system.message.messageReceiversText')"
            class="ml-2"
            v-if="getIsSend"
          >
            <a-button type="primary" color="success" @click="handlerMessageReceiverModalOpen">
              <Icon icon="material-symbols:mark-email-read-outline-sharp" />
            </a-button>
          </Tooltip>
        </Authority>
      </template>
      <template #payload="{ model, field }">
        <template
          v-if="
            FormModeEntityRef.FormMode === FormModeEnum.Add ||
            FormModeEntityRef.FormMode === FormModeEnum.Edit
          "
        >
          <component
            :is="componentItems['PayloadEditor']"
            v-model:value="model[field]"
            :readonly="getIsSend"
          />
        </template>
        <template v-else>
          <template v-if="model['Method'] === 'MSG_QUERY' && model[field]">
            <component :is="componentItems['PayloadPreview']" :value="model[field]" />
          </template>
          <template v-else-if="model['Method'] === 'MSG_NOTICE'">
            <component
              :is="componentItems['PayloadEditor']"
              v-model:value="model[field]"
              :readonly="getIsSend"
            />
          </template>
        </template>
      </template>
    </BasicForm>
    <template #insertFooter>
      <Authority :value="'Root.Admin.Msg.Message.Send'">
        <a-button
          color="success"
          @click="handleSendMessage"
          :disabled="getIsSend || FormModeEntityRef.FormMode === FormModeEnum.Add"
          :loading="loadingRef"
        >
          <Icon icon="icon-park-outline:send-email" />
          {{ t('routes.system.message.sendMessageText') }}
        </a-button>
      </Authority>
    </template>
  </AdVxeModal>

  <PrintTemplateModal @register="templateModalRegister" v-bind="templateModalProps" />
  <MessageReceiverModal @register="registerMessageReceiverModal" />
  <UserTransferModal
    @register="registerUserTransferModal"
    :title="t('routes.system.message.toUsersText')"
    :search="true"
    :okText="t('common.okText')"
    :okFunc="handleUserTransferModalOk"
    width="50%"
  />
  <OrganizationTransferModal
    @register="registerOrganizationTransferModal"
    :title="t('routes.system.message.toOrganizationsText')"
    :search="true"
    :okText="t('common.okText')"
    :okFunc="handleOrganizationTransferModalOk"
    width="50%"
  />
  <RoleTransferModal
    @register="registerRoleTransferModal"
    :title="t('routes.system.message.toRolesText')"
    :search="true"
    :okText="t('common.okText')"
    :okFunc="handleRoleTransferModalOk"
    width="50%"
  />
</template>

<script lang="ts" setup>
  import type { PropType } from 'vue';
  import { computed, h, ref } from 'vue';
  import { Select, Tooltip } from 'ant-design-vue';
  import { useMessage } from '@/hooks/web/useMessage';

  import { Authority } from '@/components/Authority';
  import { AdVxeModal, useModal, useModalInner } from '@/components/AdVxeModal';
  import { BasicForm, useForm, FormSchema } from '@/components/Form';
  import Icon from '@/components/Icon/Icon.vue';
  import { ImageSelector } from '@/components/ImageSelector';
  import { PrintTemplateModal, useAdPrint } from '@/components/AdPrint';

  import { useI18n } from '@/hooks/web/useI18n';
  import { useContextMenu } from '@/hooks/web/useContextMenu';
  import { destroyContextMenu } from '@/components/ContextMenu';
  import { isFunction } from '@/utils/is';

  import { FormModeEnum, FormModeEntity } from '@/enums/formEnum';

  import { getMessageTypeEnumSchema } from '@/enums/messageTypeEnum';
  import { getMessageLevelEnumSchema } from '@/enums/messageLevelEnum';
  import { getMessageSendWayEnumSchema } from '@/enums/messageSendWayEnum';

  import { AjaxResult } from '#/request';
  import { MessageInputDto, MessageOutputDto } from '@/api/message/admin/message/model';
  import {
    createMessages,
    updateMessages,
    deleteMessages,
    sendMessages,
  } from '@/api/message/admin/message';

  import UserTransferModal from '@/views/system/identity/user/UserTransferModal.vue';
  import OrganizationTransferModal from '@/views/system/identity/organization/OrganizationTransferModal.vue';
  import RoleTransferModal from '@/views/system/identity/role/RoleTransferModal.vue';

  import MessageReceiverModal from './receiver.vue';
  import PayloadPreview from '@/views/system/message/querymessage/PayloadPreview.vue';
  import PayloadEditor from '@/views/system/message/templatemessage/PayloadEditor.vue';

  const componentItems = { PayloadPreview, PayloadEditor };

  defineOptions({ name: 'MessageDetailModal' });
  const props = defineProps({
    /** 关闭回调，返回true关闭窗体 */
    closeFunc: {
      type: Function as PropType<
        (formMode: FormModeEnum, record: MessageOutputDto | undefined) => Promise<boolean>
      >,
      default: null,
    },
    /** 提交前回调，返回false不执行内置提交逻辑，返回true执行内置提交逻辑 */
    beforeSubmitFunc: {
      type: Function as PropType<
        (formMode: FormModeEnum, record: MessageOutputDto | undefined) => Promise<boolean>
      >,
      default: null,
    },
    /** 提交后回调，返回true关闭窗体 */
    afterSubmitFunc: {
      type: Function as PropType<
        (
          formMode: FormModeEnum,
          result: AjaxResult | null | undefined,
          record: MessageOutputDto | undefined,
        ) => Promise<boolean>
      >,
      default: null,
    },
  });
  const emit = defineEmits(['sendmsg', 'register']);

  const { t } = useI18n();
  const { createMessage } = useMessage();
  const [createContextMenu] = useContextMenu();
  const recordRef = ref<any>({});
  const formIndex = 'message_detail';
  const keyField = 'Id';

  const formModeRef = ref<FormModeEnum>(FormModeEnum.Ok);
  const FormModeEntityRef = ref<FormModeEntity>(new FormModeEntity(formModeRef.value));

  const getIsSend = computed(() => {
    return recordRef.value?.IsSent === true;
  });

  const getMessageTypes = computed(() => {
    const messageTypeEnumSchema = getMessageTypeEnumSchema();
    const messageTypes = messageTypeEnumSchema.map((item) => {
      let disabled = false;
      switch (item.value) {
        case 1: //文本消息
        case 2: //图片消息
        case 3: //语音消息
        case 4: //视屏消息
        case 5: //文件消息
        case 7: //数据消息
          disabled = true;
          break;
      }

      // console.log(item);
      return {
        label: item.label,
        value: item.value,
        disabled: disabled,
      };
    });
    return messageTypes;
  });

  const schemas: FormSchema[] = [
    {
      field: 'Icon',
      helpMessage: `${t('common.field')}：${'Icon'}`,
      // component: 'IconPicker',
      label: t('routes.system.message.iconText'),
      slot: 'icon',
      colProps: {
        // span: 24,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 24, // ≥1200px
        xxl: 24, // ≥1600px
        // xxxl: 24, // ≥2000px 3.0
      },
    },
    {
      field: 'Id',
      helpMessage: `${t('common.field')}：${'Id'}`,
      component: 'Input',
      label: t('entity.idTitle'),
      componentProps: { disabled: true },
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
    {
      field: 'Method',
      helpMessage: `${t('common.field')}：${'Method'}`,
      component: 'Input',
      label: t('routes.system.message.methodText'),
      componentProps: { disabled: true },
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
    {
      field: 'BaseType',
      helpMessage: `${t('common.field')}：${'BaseType'}`,
      component: 'Input',
      label: t('routes.system.message.message.baseTypeText'),
      componentProps: { disabled: true },
      ifShow: ({ values: _values }) => {
        return FormModeEntityRef.value.FormMode !== FormModeEnum.Add;
      },
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
    {
      field: 'BaseId',
      helpMessage: `${t('common.field')}：${'BaseId'}`,
      component: 'Input',
      label: t('routes.system.message.message.baseIdText'),
      componentProps: { disabled: true },
      ifShow: ({ values: _values }) => {
        return FormModeEntityRef.value.FormMode !== FormModeEnum.Add;
      },
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
    {
      field: 'MessageType',
      helpMessage: `${t('common.field')}：${'MessageType'}`,
      component: 'Select',
      label: t('routes.system.message.messageTypeText'),
      required: true,
      defaultValue: 6,
      render: ({ model, field }) => {
        return h(Select, {
          options: [...getMessageTypes.value],
          showSearch: true,
          optionFilterProp: 'label',
          value: model[field],
          onChange: (e: any) => {
            model[field] = e;
          },
        });
      },
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
    {
      field: 'MessageLevel',
      helpMessage: `${t('common.field')}：${'MessageLevel'}`,
      component: 'Select',
      label: t('routes.system.message.messageLevelText'),
      required: true,
      defaultValue: 2,
      render: ({ model, field }) => {
        return h(Select, {
          options: [...getMessageLevelEnumSchema()],
          showSearch: true,
          optionFilterProp: 'label',
          value: model[field],
          onChange: (e: any) => {
            model[field] = e;
          },
        });
      },
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
    {
      field: 'Title',
      helpMessage: `${t('common.field')}：${'Title'}`,
      component: 'Input',
      label: t('routes.system.message.titleText'),
      colProps: {
        // span: 24,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 24, // ≥1200px
        xxl: 24, // ≥1600px
        // xxxl: 24, // ≥2000px 3.0
      },
    },
    {
      field: 'Content',
      helpMessage: `${t('common.field')}：${'Content'}`,
      component: 'InputTextArea',
      label: t('routes.system.message.contentText'),
      colProps: {
        // span: 24,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 24, // ≥1200px
        xxl: 24, // ≥1600px
        // xxxl: 24, // ≥2000px 3.0
      },
    },
    {
      field: 'SendTime',
      helpMessage: `${t('common.field')}：${'SendTime'}`,
      component: 'DatePicker',
      componentProps: {
        showTime: true,
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        style: { width: '100%' },
      },
      dynamicDisabled: () => {
        if (FormModeEntityRef.value.FormMode === FormModeEnum.Add) {
          return false;
        }
        if (FormModeEntityRef.value.FormMode === FormModeEnum.Edit) {
          return getIsSend.value;
        }
        return true;
      },
      label: t('routes.system.message.message.sendTimeText'),
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
    {
      field: 'StorageDays',
      helpMessage: `${t('common.field')}：${'StorageDays'} [${t(
        'routes.system.message.storageDaysHelpText',
      )}]`,
      component: 'InputNumber',
      componentProps: {
        min: 0,
        max: 365,
        defaultValue: 0,
        style: { width: '100%' },
      },
      dynamicDisabled: () => {
        if (FormModeEntityRef.value.FormMode === FormModeEnum.Add) {
          return false;
        }
        if (FormModeEntityRef.value.FormMode === FormModeEnum.Edit) {
          return getIsSend.value;
        }
        return true;
      },
      label: t('routes.system.message.storageDaysText'),
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
    {
      field: 'SendWays',
      helpMessage: `${t('common.field')}：${'SendWays'}`,
      component: 'Select',
      label: t('routes.system.message.sendWaysText'),
      required: true,
      render: ({ model, field }) => {
        let disabled = true;
        if (FormModeEntityRef.value.FormMode === FormModeEnum.Add) {
          disabled = false;
        } else if (FormModeEntityRef.value.FormMode === FormModeEnum.Edit) {
          disabled = getIsSend.value;
        }
        return h(Select, {
          mode: 'multiple',
          options: [...getMessageSendWayEnumSchema()],
          showSearch: true,
          disabled,
          optionFilterProp: 'label',
          value: model[field],
          onChange: (e: any) => {
            model[field] = e;
            // console.log('SendWays', e);
          },
        });
      },
      colProps: {
        // span: 24,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 24, // ≥1200px
        xxl: 24, // ≥1600px
        // xxxl: 24, // ≥2000px 3.0
      },
    },
    {
      field: 'SendTo',
      // component: 'Input',
      slot: 'sendTo',
      label: t('routes.system.message.sendToText'),
      colProps: {
        // span: 24,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 24, // ≥1200px
        xxl: 24, // ≥1600px
        // xxxl: 24, // ≥2000px 3.0
      },
    },
    {
      field: 'Payload',
      helpMessage: `${t('common.field')}：${'Payload'}`,
      // component: 'Input',
      label: t('routes.system.message.payloadText'),
      slot: 'payload',
      colProps: {
        // span: 16,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 24, // ≥1200px
        xxl: 24, // ≥1600px
        // xxxl: 24, // ≥2000px 3.0
      },
    },
    {
      field: 'ToUsers',
      component: 'Select',
      label: t('routes.system.message.toUsersText'),
      defaultValue: [],
      show: false,
    },
    {
      field: 'ToOrganizations',
      component: 'Select',
      label: t('routes.system.message.toOrganizationsText'),
      show: false,
    },
    {
      field: 'ToRoles',
      component: 'Select',
      label: t('routes.system.message.toRolesText'),
      show: false,
    },
    {
      field: 'IsSystem',
      helpMessage: `${t('common.field')}：${'IsSystem'}`,
      component: 'Switch',
      ifShow: () => FormModeEntityRef.value.FormMode !== FormModeEnum.Add,
      dynamicDisabled: true,
      label: t('routes.system.message.message.isSystemText'),
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
    {
      field: 'IsSent',
      helpMessage: `${t('common.field')}：${'IsSent'}`,
      component: 'Switch',
      ifShow: () => FormModeEntityRef.value.FormMode !== FormModeEnum.Add,
      dynamicDisabled: true,
      label: t('routes.system.message.message.isSentText'),
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
    {
      field: 'SenderName',
      helpMessage: `${t('common.field')}：${'SenderName'}`,
      component: 'Input',
      label: t('routes.system.message.message.senderNameText'),
      ifShow: ({ model, field }) => {
        const value = model[field];
        return value !== undefined && value !== null && value !== '';
      },
      componentProps: { disabled: true },
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
    {
      field: 'SenderNickname',
      helpMessage: `${t('common.field')}：${'SenderNickname'}`,
      component: 'Input',
      label: t('routes.system.message.message.senderNicknameText'),
      ifShow: ({ model, field }) => {
        const value = model[field];
        return value !== undefined && value !== null && value !== '';
      },
      componentProps: { disabled: true },
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
    {
      field: 'CreatedTime',
      helpMessage: `${t('common.field')}：${'CreatedTime'}`,
      component: 'DatePicker',
      label: t('entity.creationAudited.createdTimeTitle'),
      componentProps: {
        disabled: true,
        showTime: true,
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        style: { width: '100%' },
      },
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
  ];

  const [registerForm, { resetFields, getFieldsValue, setFieldsValue, validate }] = useForm({
    labelWidth: 150,
    schemas: schemas,
    showActionButtonGroup: false,
    compact: true,
  });

  const [register, { setModalProps, closeModal, changeLoading }] = useModalInner(async (data) => {
    changeLoading(true);
    try {
      await clearInputDto();
      recordRef.value = data.record;
      if (data.formMode) {
        formModeRef.value = data.formMode as FormModeEnum;
        FormModeEntityRef.value = new FormModeEntity(formModeRef.value);
        switch (formModeRef.value) {
          case FormModeEnum.Add:
            break;
          case FormModeEnum.Edit:
          case FormModeEnum.ReadOnly:
          case FormModeEnum.Ok:
            break;
        }
      }
      if (recordRef.value) {
        await setInputDto({
          ...recordRef.value,
        });
      }
    } finally {
      changeLoading(false);
    }
  });

  //#region "加载状态"
  const loadingRef = ref(false);
  /** 开启加载状态 */
  function openLoading() {
    changeLoading(true);
    setModalProps({ okLoading: true, cancelLoading: true });
    loadingRef.value = true;
  }
  /** 关闭加载状态 */
  function closeLoading() {
    changeLoading(false);
    setModalProps({ okLoading: false, cancelLoading: false });
    loadingRef.value = false;
  }
  //#endregion
  //#region 定义高级打印
  const { printContextMenus, templateModalRegister, templateModalProps } = useAdPrint({
    formIndex: formIndex,
    keyField: keyField,
    getFormData: () => getFieldsValue(),
  });
  /** 处理上下文菜单(右键菜单) */
  function handleContextMenu(e: MouseEvent) {
    const element = document.elementFromPoint(e.clientX, e.clientY) as Element;
    const cursor = document.defaultView?.getComputedStyle(element, null).cursor;
    // console.log('handleContextMenu', {
    //   cursor: cursor,
    // });

    let items: any[] = [];
    switch (FormModeEntityRef.value.FormMode) {
      case FormModeEnum.Ok:
      case FormModeEnum.Edit:
      case FormModeEnum.ReadOnly:
        if (!cursor || cursor === 'default' || cursor === 'auto') {
          items = [...printContextMenus];
        }
        break;
    }
    if (items && items?.length > 0) {
      createContextMenu({
        event: e,
        styles: {
          border: '1px solid #eee',
          'border-radius': '2px',
          'box-shadow': '3px 3px 3px rgb(0 0 0 / 15%)',
        },
        items: [...items],
      });
    }
  }
  //#endregion

  /** 获取输入DTO */
  function getInputDto(): MessageInputDto {
    const record = getFieldsValue() as MessageInputDto;
    return record;
  }
  /** 设置输入DTO */
  async function setInputDto(values: any) {
    let inputDto = getInputDto();
    inputDto = { ...inputDto, ...values };
    await setFieldsValue({ ...inputDto });
  }
  /** 清除输入DTO */
  async function clearInputDto() {
    await resetFields();
  }

  /** 获取输出DTO */
  function getOutputDto(): MessageOutputDto {
    const record = getFieldsValue() as MessageOutputDto;
    return record;
  }

  /** 处理关闭按钮 */
  async function handleClose() {
    openLoading();

    const { closeFunc } = props;
    try {
      if (closeFunc && isFunction(closeFunc)) {
        const outputDto = getOutputDto();
        const result = await closeFunc(FormModeEntityRef.value.FormMode, outputDto);
        return result;
      }
    } finally {
      closeLoading();
    }
    return true;
  }
  /** 处理确定按钮 */
  async function handleOk() {
    const data = await validate();
    if (!data) return;
    //console.log(data);

    openLoading();
    const { beforeSubmitFunc, afterSubmitFunc } = props;
    try {
      const inputDto = getInputDto();
      const outputDto = getOutputDto();
      // console.log('handleOk', inputDto);
      let innerSubmit = true;
      let innerCloseModal = true;
      if (beforeSubmitFunc && isFunction(beforeSubmitFunc)) {
        innerSubmit = await beforeSubmitFunc(FormModeEntityRef.value.FormMode, outputDto);
      }
      let result: AjaxResult | null = null;
      if (innerSubmit) {
        switch (FormModeEntityRef.value.FormMode) {
          case FormModeEnum.Add:
            result = await createMessages([inputDto]);
            break;
          case FormModeEnum.Edit:
            result = await updateMessages([inputDto]);
            break;
          case FormModeEnum.Delete:
            result = await deleteMessages([inputDto.Id]);
            break;
        }
      }
      if (afterSubmitFunc && isFunction(afterSubmitFunc)) {
        innerCloseModal = await afterSubmitFunc(
          FormModeEntityRef.value.FormMode,
          result,
          outputDto,
        );
      }
      if (innerCloseModal) {
        closeModal();
      }
    } finally {
      closeLoading();
    }
  }
  /** 打开或者关闭触发 */
  function handleOpenChange(open: boolean) {
    if (!open) {
      destroyContextMenu();
    }
  }

  //#region "设置用户"
  const [registerUserTransferModal, userTransferModalMethods] = useModal();
  /** 处理打开设置用户弹窗 */
  async function handleUserTransferModalOpen() {
    const inputDto = getInputDto();
    userTransferModalMethods.openModal(true, {
      checkedKeys: inputDto.ToUsers,
      record: inputDto,
    });
    userTransferModalMethods.setModalProps({
      title: `${t('routes.system.message.toUsersText')}`,
    });
  }
  /** 处理设置用户弹窗确定按钮 */
  async function handleUserTransferModalOk(targetKeys: string[], _nodes: any[], _record: any) {
    switch (FormModeEntityRef.value.FormMode) {
      case FormModeEnum.Add:
      case FormModeEnum.Edit:
        if (targetKeys) {
          await setInputDto({
            ToUsers: targetKeys,
          });
        }
        break;
    }
    return true;
  }
  //#endregion

  //#region "设置组织"
  const [registerOrganizationTransferModal, organizationTransferModalMethods] = useModal();
  /** 处理打开设置组织机构弹窗 */
  async function handleOrganizationTransferModalOpen() {
    const inputDto = getInputDto();
    organizationTransferModalMethods.openModal(true, {
      checkedKeys: inputDto.ToOrganizations,
      record: inputDto,
    });
    organizationTransferModalMethods.setModalProps({
      title: `${t('routes.system.message.toOrganizationsText')}`,
    });
  }
  /** 处理设置组织机构弹窗确定按钮 */
  async function handleOrganizationTransferModalOk(
    targetKeys: string[],
    _nodes: any[],
    _record: any,
  ) {
    switch (FormModeEntityRef.value.FormMode) {
      case FormModeEnum.Add:
      case FormModeEnum.Edit:
        if (targetKeys) {
          await setInputDto({
            ToOrganizations: targetKeys,
          });
        }
        break;
    }
    return true;
  }
  //#endregion

  //#region "设置角色"
  const [registerRoleTransferModal, roleTransferModalMethods] = useModal();
  /** 处理打开设置角色弹窗 */
  async function handleRoleTransferModalOpen() {
    const inputDto = getInputDto();
    roleTransferModalMethods.openModal(true, {
      checkedKeys: inputDto.ToRoles,
      record: inputDto,
    });
    roleTransferModalMethods.setModalProps({
      title: `${t('routes.system.message.toRolesText')}`,
    });
  }
  /** 处理设置角色弹窗确定按钮 */
  async function handleRoleTransferModalOk(
    targetKeys: (string | bigint)[],
    _nodes: any[],
    _record: any,
  ) {
    switch (FormModeEntityRef.value.FormMode) {
      case FormModeEnum.Add:
      case FormModeEnum.Edit:
        if (targetKeys) {
          await setInputDto({
            ToRoles: targetKeys,
          });
        }
        break;
    }
    return true;
  }
  //#endregion

  //#region "设置消息接收者弹窗"
  const [registerMessageReceiverModal, messageReceiverModalMethods] = useModal();
  /** 处理打开消息接收者弹窗 */
  async function handlerMessageReceiverModalOpen() {
    const inputDto = getInputDto();
    messageReceiverModalMethods.openModal(true, {
      record: inputDto,
    });
  }
  //#endregion

  /** 处理发送 */
  async function handleSendMessage() {
    if (FormModeEntityRef.value.FormMode !== FormModeEnum.Add) {
      const inputDto = getInputDto();
      // console.log('inputDto', inputDto);
      if (inputDto?.Id) {
        openLoading();
        try {
          var reulst = await sendMessages([inputDto.Id]);
          if (reulst.Succeeded) {
            createMessage.success(t('common.successText'));
            emit('sendmsg', inputDto);
            closeModal();
          }
        } finally {
          closeLoading();
        }
      }
    }
  }
</script>

<style lang="less" scoped></style>
